Namespace PL.MESSDK

    Public Interface ILotTransaction_PL
        Function ReleaseLine(ByVal dataRow As DataRow) As Boolean
        Function ConfirmLine(ByVal dataRow As DataRow) As Boolean
        Function ReserveLine(ByVal dataRow As DataRow) As Boolean
        Function RevertLine(ByVal dataRow As DataRow) As Boolean
    End Interface
    Public Class LotTransaction_PL
        Inherits PLBase
        Implements IPLProcess, ILotTransaction_PL

        Public Sub New(ByVal queryName As String)
            MyBase.New(queryName)
        End Sub

        Public Sub New()
            MyBase.New()
        End Sub

        Public Overrides Function Delete() As Boolean
            'Throw New NotImplementedException("Delete To Come...")
            Return False
        End Function

        Public Overrides Function Validate() As Boolean
            'Throw New NotImplementedException("Validate To Come...")
            Return True
        End Function
        ''' <summary>
        ''' Valider si on a le droit de changer le statut d'un lot. 
        ''' Cette validation ce fait avec via la table LotBuisnessFlow
        ''' </summary>
        ''' <param name="lotId"></param>
        ''' <param name="newStatusId"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Overridable Function ValidateStatusChange(ByVal lotId As Guid, newStatusId As Guid) As Boolean
            Return True
        End Function

        Public Overrides Sub ValidateRow(row As DataRow)

            Dim aSiteSectionRow As DataRow = Nothing

            row.ClearErrors()
            'Mandatory Fields
            'TODO: Cache MetaString in AppManager, so here we read it once maybe for nothing
            'Dim ms As MetaString
            'ms = MetaString.GetMetaStringByCode("Mandatory", AppManager.ApplicationOption.LanguageId)
            If IsDBNull(row("LotTranID")) Then
                row.SetColumnError("LotTranID", "Mandatory")
            End If

            If IsDBNull(row("Qty")) Then
                row.SetColumnError("Qty", "Mandatory")
            End If

            If IsDBNull(row("TranUnitId_FK")) Then
                row.SetColumnError("TranUnitId_FK", "Mandatory")
            End If

            If IsDBNull(row("StatusID_FK")) Then
                row.SetColumnError("StatusID_FK", "Mandatory")
            End If

            If IsDBNull(row("TranDate")) Then
                row.SetColumnError("TranDate", "Mandatory")
            End If

            If IsDBNull(row("LotTypeId_FK")) Then
                row.SetColumnError("LotTypeId_FK", "Mandatory")
            End If
            '
            If Not IsDBNull(row("TranTypeID_FK")) Then
                Select Case DirectCast(row("TranTypeID_FK"), Guid)
                    Case IdRepository.APP_TRAN_ISSUEWIP
                        If IsDBNull(row("FROMWhBinID_FK")) Then
                            row.SetColumnError("FROMWhBinID_FK", "Mandatory")
                        End If
                        If IsDBNull(row("TOWhBinID_FK")) Then
                            row.SetColumnError("TOWhBinID_FK", "Mandatory")
                        End If
                    Case IdRepository.APP_TRAN_RCPT
                        '
                        If IsDBNull(row("RefDoc")) Then
                            row.SetColumnError("RefDoc", "Mandatory")
                        End If

                        If IsDBNull(row("PrdId_FK")) AndAlso IsDBNull(row("LotCD")) AndAlso IsDBNull(row("LotID_FK")) Then
                            row.SetColumnError("LotID_FK", "Mandatory")
                            row.SetColumnError("PrdId_FK", "Mandatory")
                            row.SetColumnError("LotCD", "Mandatory")
                        End If
                        '
                        If Not IsDBNull(row("PrdId_FK")) AndAlso IsDBNull(row("LotCD")) Then
                            row.SetColumnError("LotCD", "Mandatory")
                        End If
                        '
                        If Not IsDBNull(row("LotCD")) AndAlso IsDBNull(row("PrdId_FK")) Then
                            row.SetColumnError("PrdId_FK", "Mandatory")
                        End If
                        '
                        If IsDBNull(row("TOWhBinID_FK")) Then
                            row.SetColumnError("TOWhBinID_FK", "Mandatory")
                        End If
                        If IsDBNull(row("Qty")) OrElse CDec(row("Qty")) <= 0 Then
                            row.SetColumnError("Qty", "Quantity must be greater than 0, for a reception")
                        End If

                    Case IdRepository.APP_TRAN_ADJMNT
                        If IsDBNull(row("LotID_FK")) Then
                            row.SetColumnError("LotID_FK", "Mandatory")
                        End If
                        If IsDBNull(row("FROMWhBinID_FK")) Then
                            row.SetColumnError("FROMWhBinID_FK", "Mandatory")
                        End If
                        If IsDBNull(row("TOWhBinID_FK")) Then
                            row.SetColumnError("TOWhBinID_FK", "Mandatory")
                        End If

                    Case IdRepository.APP_TRAN_PHYCNT, IdRepository.APP_TRAN_PHYCNTINV
                        If IsDBNull(row("LotID_FK")) Then
                            row.SetColumnError("LotID_FK", "Mandatory")
                        End If

                        If IsDBNull(row("FROMWhBinID_FK")) Then
                            row.SetColumnError("FROMWhBinID_FK", "Mandatory")
                        End If

                        If IsDBNull(row("TOWhBinID_FK")) Then
                            row.SetColumnError("TOWhBinID_FK", "Mandatory")
                        End If
                    Case IdRepository.APP_TRAN_SALES
                        If IsDBNull(row("LotID_FK")) Then
                            row.SetColumnError("LotID_FK", "Mandatory")
                        End If

                        aSiteSectionRow = ValidateFromSiteSection(row)
                        If aSiteSectionRow IsNot Nothing Then
                            If aSiteSectionRow("QtyOnHand") <= 0 Then
                                row.SetColumnError("FROMWhBinID_FK", "No Qty On Hand")
                            End If
                        End If
                    Case IdRepository.APP_TRAN_TRNFER, IdRepository.APP_TRAN_RTRNTOSTOCK, IdRepository.APP_TRAN_SPLIT, IdRepository.APP_TRAN_WTRAN
                        If IsDBNull(row("LotID_FK")) Then
                            row.SetColumnError("LotID_FK", "Mandatory")
                        End If
                        If Not IsDBNull(row("Qty")) AndAlso CDec(row("Qty")) <= 0 Then
                            row.SetColumnError("Qty", "Quantity must be greater than 0, for a Transfert/Return")
                        End If

                        aSiteSectionRow = ValidateFromSiteSection(row)
                        If aSiteSectionRow IsNot Nothing Then
                            If aSiteSectionRow("QtyOnHand") <= 0 Then
                                row.SetColumnError("FROMWhBinID_FK", "No Qty Available")
                            End If
                        End If

                        If IsDBNull(row("TOWhBinID_FK")) Then
                            row.SetColumnError("TOWhBinID_FK", "Mandatory")
                        End If
                    Case Else
                End Select
            End If

            If row.HasErrors Then
                row.RowError = "Please check your columns, a validation error occur"
            End If
        End Sub

        ''' <summary>
        ''' Validate the FromSiteSection existe for a lot.
        ''' Check in table LotStock and Mandatory.
        ''' </summary>
        ''' <param name="row"></param>
        ''' <remarks></remarks>
        Public Shared Function ValidateFromSiteSection(ByVal row As DataRow) As DataRow
            Dim aSiteSectionRow As DataRow = Nothing
            If IsDBNull(row("FROMWhBinID_FK")) Then
                row.SetColumnError("FROMWhBinID_FK", "Mandatory")
            ElseIf Not IsDBNull(row("LotID_FK")) Then
                aSiteSectionRow = Lot_PL.GetLotSectionByID(CType(row("LotID_FK"), Guid), CType(row("FROMWhBinID_FK"), Guid))
                If aSiteSectionRow Is Nothing Then
                    row.SetColumnError("FROMWhBinID_FK", "Invalide Site section for this Lot")
                End If
            Else
                row.SetColumnError("LotID_FK", "Mandatory")
            End If
            Return aSiteSectionRow
        End Function

        ''' <summary>
        ''' Valider si on a le droit de faire une transaction sur un lot. 
        ''' Cette validation ce fait avec via la table LotBuisnessFlow
        ''' </summary>
        ''' <param name="lotId"></param>
        ''' <param name="newTranTypeId"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Overridable Function ValidateLotTransaction(ByVal lotId As Guid, ByVal newTranTypeId As Guid) As Boolean
            'Dim lbflow As DataTable
            'aller chercher le lot
            'lbflow = LotBusinessFlow_PL.GetLotBusinessFlow(newTranTypeId, Lot.LotType, Lot.Status)

            'Parmis les lbflow trouver, avons nous le droit de faire ca

            'Si pas de résultat trouvé on a pas le droit.

            Return True
        End Function

        'Public Overridable Function SiteSectionTransfer(ByVal lotId As Guid, ByVal qty As Double, ByVal fromSiteSectionId As Guid, ByVal toSiteSectionId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
        '    Return True
        'End Function

        'Public Overridable Function AdjustmentCount(ByVal lotId As Guid, ByVal qty As Double, ByVal unitId As Guid, ByVal siteSectionId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
        '    Return True
        'End Function

        'Public Overridable Function PhysicalCount(ByVal lotId As Guid, ByVal qty As Double, ByVal unitId As Guid, ByVal siteSectionId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
        '    Return True
        'End Function

        'Public Overridable Function ReturnToStock(ByVal lotId As Guid, ByVal qty As Double, ByVal unitId As Guid, ByVal siteSectionId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
        '    Return True
        'End Function

        Public Overridable Function ChangeLotStatus(ByVal lotId As Guid, statusId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("ChangeLotStatus")
                '
                sqlcmd.Parameters("@LotID").Value = lotId
                sqlcmd.Parameters("@TOLotStatusId_FK").Value = statusId
                sqlcmd.Parameters("@RefDoc").Value = referenceDocument
                '
                sqlcmd.ExecuteNonQuery()
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        'Public Overridable Function GetLastTransaction(ByVal lotId As Guid) As Boolean
        '    Return True
        'End Function

        Public Function BatchRecords(dataRow() As System.Data.DataRow) As Boolean Implements IPLProcess.BatchRecords
            Return True
        End Function

        Public Function CurrentRecord(dataRow As System.Data.DataRow) As Boolean Implements IPLProcess.CurrentRecord
            Return True
        End Function

        Public Function NewRecord(dataRow As System.Data.DataRow) As Boolean Implements IPLProcess.NewRecord
            dataRow("LotTranID") = Guid.NewGuid
            Return True
        End Function

        Public Shared Function ProcessBatchTransaction(ByVal lotTranId As Guid) As Boolean
            Dim sqlcmd As SqlCommand = Nothing
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("bsp_ProcessLotTransaction")
                sqlcmd.Parameters("@LotTranID").Value = lotTranId
                sqlcmd.ExecuteNonQuery()
                Return True
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        Public Overridable Function ConfirmLine(dataRow As System.Data.DataRow) As Boolean Implements ILotTransaction_PL.ConfirmLine
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("LotTranConfirmLine")

                sqlcmd.Parameters("@LotTranID").Value = dataRow("LotTranID")
                sqlcmd.Parameters("@RecordVersion").Value = dataRow("RecordVersion")

                sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        Public Overridable Function RevertLine(dataRow As System.Data.DataRow) As Boolean Implements ILotTransaction_PL.RevertLine
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("LotTranRevertLine")   'TODO: Faire la MQ et la SP + Tester

                sqlcmd.Parameters("@LotTranID").Value = dataRow("LotTranID")
                sqlcmd.Parameters("@RecordVersion").Value = dataRow("RecordVersion")

                sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        Public Overridable Function ReleaseLine(dataRow As System.Data.DataRow) As Boolean Implements ILotTransaction_PL.ReleaseLine
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("LotTranReleaseLine")
                sqlcmd.Parameters("@LotTranID").Value = dataRow("LotTranID")
                sqlcmd.Parameters("@RecordVersion").Value = dataRow("RecordVersion")

                'NonQuery is used because bsp_LotTranReleaseLine does not return a resultset
                sqlcmd.ExecuteNonQuery()
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        Public Overridable Function ReserveLine(dataRow As System.Data.DataRow) As Boolean Implements ILotTransaction_PL.ReserveLine
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("LotTranReserveLine")
                sqlcmd.Parameters("@LotTranID").Value = dataRow("LotTranID")
                sqlcmd.Parameters("@RecordVersion").Value = dataRow("RecordVersion")

                sqlcmd.ExecuteNonQuery()
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw sqlex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return False
        End Function

        Public Shared Function SetTransactionStatus(ByVal LotTranID As Guid, ByVal fromStatus As Guid, ByVal toStatus As Guid) As Boolean
            Dim sqlcmd As SqlCommand = Nothing
            '
            Try

                sqlcmd = MetaQuery.GetSPCmdByMetaName("bsp_LotTransaction_Change_Status")
                sqlcmd.Parameters("@LotTranID").Value = LotTranID
                sqlcmd.Parameters("@InvBatchID_FK").Value = DBNull.Value
                sqlcmd.Parameters("@FromStatusID").Value = fromStatus
                sqlcmd.Parameters("@ToStatusID").Value = toStatus
                sqlcmd.ExecuteNonQuery()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return True
        End Function
    End Class

End Namespace
